package com.xiaoh.dormitoryrepairreportbackend.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaoh.dormitoryrepairreportbackend.common.ErrorCode;
import com.xiaoh.dormitoryrepairreportbackend.exception.BusinessException;
import com.xiaoh.dormitoryrepairreportbackend.mapper.UserStudentMapper;
import com.xiaoh.dormitoryrepairreportbackend.model.entity.UserStudent;
import com.xiaoh.dormitoryrepairreportbackend.service.UserStudentService;
import org.springframework.stereotype.Service;

/**
 * 学生信息表 服务实现类
 */
@Service
public class UserStudentServiceImpl extends ServiceImpl<UserStudentMapper, UserStudent>
        implements UserStudentService {

    @Override
    public boolean updateDormitoryName(Long userId, String dormitoryName) {
        if (userId == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户ID不能为空");
        }

        if (StrUtil.isBlank(dormitoryName)) {
            return true; // 如果宿舍地址为空，不更新
        }

        QueryWrapper<UserStudent> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        UserStudent userStudent = this.getOne(queryWrapper);

        if (userStudent == null) {
            // 如果学生信息不存在，创建新记录
            userStudent = new UserStudent();
            userStudent.setUserId(userId);
            userStudent.setDormitoryName(dormitoryName);
            return this.save(userStudent);
        } else {
            // 更新现有记录
            userStudent.setDormitoryName(dormitoryName);
            return this.updateById(userStudent);
        }
    }
}
